<template>
  <div style="background-color: #fafbff">
    <div id="uploadApp">
      <el-upload
        class="file-uploader"
        :show-file-list="false"
        action="#"
        :http-request="handleFileUpload"
        :accept="'.apk,.ipa'"
        style="
          width: 100%;
          margin-top: 30px;
          background-color: #f5f5f5;
          display: flex;
          flex-direction: column;
          align-items: center;
        "
      >
        <div style="padding: 200px">
          <i
            style="
              display: block;
              padding: 10px 40px;
              background: linear-gradient(#8e8cf9, #56a1f9);
              color: #fff;
            "
            >选择文件</i
          >
          <p style="margin: 30px 0 10px 0">
            点击按钮选择应用的安装包，或拖拽文件到此区域
          </p>
          <p>（支持.ipa或.apk文件，单个文件最大支持3G）</p>
        </div>
      </el-upload>
      <div style="margin: 30px 0; background-color: #e7eef4; padding: 10px">
        <i style="color: red">温馨提示：</i>
        <p style="margin: 15px 0">
          本平台严禁上传色情、反动、政治、非法博彩类，微信红包、虚拟币交易、金融投资、配资、非法借贷类应用，违反该规则的
          App 将被删除，屡次上传者将被删除应用并封禁账号，请严格遵守！
        </p>
        <p>
          上传前请先阅读用户协议<em
            style="color: #5dadfb; cursor: pointer"
            @click="$router.push('/companyProfile?value=4')"
            >《欧啦云应用分发平台用户协议》</em
          >
          ，一经使用即代表您同意并接受本协议的所有条件和条款。
        </p>
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <div
        style="
          display: flex;
          align-items: center;
          border: 1px solid #dcdfe6;
          padding: 0 30px;
        "
      >
        <p style="font-size: 25px">应用:</p>
        <div>
          <img
            :src="appicon"
            alt=""
            style="width: 100px; height: 100px; margin: 20px 20px"
          />
        </div>
        <div style="font-size: 18px">
          <p>{{ form.in_name }}</p>
          <p>{{ form.in_form }}</p>
        </div>
        <p style="font-size: 25px; margin-left: 20px">版本号:</p>
        <p style="font-size: 25px">{{ form.in_mnvs }}</p>
      </div>

      <el-divider></el-divider>
      <div
        style="
          display: flex;
          align-items: center;
          border: 1px solid #dcdfe6;
          padding: 30px;
          flex-direction: column;
        "
      >
        <!-- <el-progress type="circle" :percentage="percentage"></el-progress> -->
        <el-progress
          :text-inside="false"
          :stroke-width="26"
          :percentage="percentage"
          style="width: 100%"
          :show-text="false"
        />
        <el-button
          style="width: 95px; height: 40px; margin: 10px 0"
          @click="uploading"
          :disabled="disabled"
          >上传文件</el-button
        >
        <p style="font-size: 21px; font-weight: 400">
          {{ loadedInMB }} / {{ sizeInMB }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js';
import AppInfoParser from 'app-info-parser/dist/app-info-parser.min';
import { getToken, app_up, app_update } from '@/api/fenfa';
import { config } from '@/api/index';
import { mapState } from 'vuex';

export default {
  data() {
    return {
      witheName: null,
      blackList: [],
      loadedInMB: '0MB',
      sizeInMB: '0MB',
      disabled: false,
      appicon: '',
      dialogVisible: false,
      messageData: null,
      percentage: 0,
      token: '',
      form: {
        in_name: '',
        in_icon: '',
        in_form: '',
        in_bid: '',
        in_bsvs: '1.0.0',
        in_mnvs: null,
        in_app: '',
        in_originalName: '',
        in_size: ''
      },
      subscription: null
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user
    })
  },
  methods: {
    uploading() {
      this.disabled = true;
      // 点击上传
      this.uploadfun(this.messageData);
    },

    handleFileUpload(files) {
      const file = files.file;
      const isLt = file.size / 1024 / 1024 / 1024 < 0.3;
      const isLt1 = file.size / 1024 / 1024 / 1024 < 0.5;
      const isLt2 = file.size / 1024 / 1024 / 1024 < 1;
      const isLt3 = file.size / 1024 / 1024 / 1024 < 3;
      if (this.userInfo.in_svip === '体验会员' && !isLt)
        return this.$message.error('单文件大小超过300MB，请开通或升级会员!');
      if (this.userInfo.in_svip === '初级会员' && !isLt1)
        return this.$message.error('单文件大小超过500MB，请开通或升级会员!');
      if (this.userInfo.in_svip === '中级会员' && !isLt2)
        return this.$message.error('单文件大小超过1GB，请开通或升级会员!');
      if (this.userInfo.in_svip === '高级会员' && !isLt3)
        return this.$message.error('单文件大小超过3GB，请开通或升级会员!');
      this.form.in_bid = file.name;
      this.form.in_originalName = file.name;
      this.messageData = file;
      this.form.in_size = file.size;
      this.sizeInMB = (file.size / (1024 * 1024)).toFixed(2) + 'MB';
      if (file.name.substring(file.name.length - 3) == 'apk') {
        this.form.in_form = 'Android';
      } else {
        this.form.in_form = 'iOS';
      }
      // 获取的文件对象 file
      const parser = new AppInfoParser(file);
      parser.parse().then((res) => {
        if (this.form.in_form == 'Android') {
          this.form.in_name = res.application.label[0];
          if (
            this.blackList.findIndex((res) => res === this.form.in_name) !== -1
          )
            return this.$message.error('此应用为黑名单应用，禁止上传');

          this.form.in_mnvs = res.versionName;
        } else {
          // 优先选择CFBundleDisplayName，如果不存在，则选择CFBundleName作为应用程序名称
          this.form.in_name = res.CFBundleDisplayName || res.CFBundleName;
          this.form.in_bid = res.CFBundleIdentifier;
          if (
            this.blackList.findIndex((res) => res === this.form.in_name) !== -1
          )
            return this.$message.error('此应用为黑名单应用，禁止上传');
          this.form.in_mnvs = res.DTPlatformVersion;
        }
        if (this.witheName && this.witheName !== this.form.in_name)
          return this.$message.warning('更新应用名请与原应用名保持一致');
        this.form.in_type = '1';
        this.appicon = res.icon
          ? res.icon
          : '';
        const base64String = res.icon
          ? res.icon
          : '';
        this.dialogVisible = true;
        // 将base64图片转码
        const blob = this.base64ToBlob(base64String);
        const options = {
          quality: 0.92,
          noCompressIfLarger: true
        };
        // 上传图片
        qiniu.compressImage(blob, options).then((data) => {
          const compressedBlob = data.dist;
          this.uploadToQiniu(compressedBlob);
        });
      });
    },
    uploadfun(file) {
      const that = this;
      const key = 'apply' + Date.now().toString() + file.name.slice(-4);
      const observer = {
        next(res) {
          that.percentage = Math.floor(res.total.percent);
          that.loadedInMB =
            (res.total.loaded / (1024 * 1024)).toFixed(2) + 'MB';
        },
        error() {
          that.$message.error('云服务器提取失败，请重试。');
          that.subscription.unsubscribe();
        },
        complete(res) {
          that.form.in_app = res.key;
          that.$message.success('上传成功');
          that.form.in_id ? app_update(that.form) : app_up(that.form);
          setTimeout(() => {
            that.$router.push('/fenfa');
          }, 1500);
        }
      };
      const observable = qiniu.upload(file, key, this.token);
      this.subscription = observable.subscribe(observer);
    },

    base64ToBlob(base64Data) {
      const arr = base64Data.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //  上传图片函数
    uploadToQiniu(blob) {
      const that = this;
      const observable = qiniu.upload(blob, this.key, this.token);
      const observer = {
        complete(res) {
          // 处理上传完成
          that.form.in_icon = res.key;
        }
      };
      observable.subscribe(observer);
    }
  },
  watch: {
    dialogVisible(newval) {
      if (!newval) {
        if (this.subscription) {
          this.subscription.unsubscribe(); // 取消上传
          this.$message.info('上传已取消');
          setTimeout(() => {
            location.reload();
          }, 1000);
        }
      }
    }
  },
  created() {
    getToken().then((res) => {
      this.token = res.data;
    });
    config().then((res) => {
      this.blackList = res.data.black_word.split(',');
    });
    if (this.$route.query.id) {
      this.form.in_id = this.$route.query.id;
      this.witheName = this.$route.query.witheName;
    }
  }
};
</script>

<style scoped lang="scss">
#uploadApp {
  width: 1200px;
  margin: 0 auto;
  padding: 10px;
  background-color: #fff;
}

.file-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.file-uploader .el-upload:hover {
  border-color: #409eff;
}

.file-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.file {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
